<?php
	require('config.php');
	 /** 
    * Respose A Http Request 
    * 
    * @param string $url 
    * @param array $post 
    * @param string $method 
    * @param bool $returnHeader 
    * @param string $cookie 
    * @param bool $bysocket 
    * @param string $ip 
    * @param integer $timeout 
    * @param bool $block 
    * @return string Response 
    */  
    function httpRequest($url,$post='',$method='GET',$limit=0,$returnHeader=FALSE,$cookie='',$bysocket=FALSE,$ip='',$timeout=15,$block=TRUE) {  
       $return = '';  
       $matches = parse_url($url);  
       !isset($matches['host']) && $matches['host'] = '';  
       !isset($matches['path']) && $matches['path'] = '';  
       !isset($matches['query']) && $matches['query'] = '';  
       !isset($matches['port']) && $matches['port'] = '';  
       $host = $matches['host'];  
       $path = $matches['path'] ? $matches['path'].($matches['query'] ? '?'.$matches['query'] : '') : '/';  
       $port = !empty($matches['port']) ? $matches['port'] : 80;  
       if(strtolower($method) == 'post') {  
           $post = (is_array($post) and !empty($post)) ? http_build_query($post) : $post;  
           $out = "POST $path HTTP/1.0\r\n";  
           $out .= "Accept: */*\r\n";  
           //$out .= "Referer: $boardurl\r\n";  
           $out .= "Accept-Language: zh-cn\r\n";  
           $out .= "Content-Type: application/x-www-form-urlencoded\r\n";  
           $out .= "User-Agent: $_SERVER[HTTP_USER_AGENT]\r\n";  
           $out .= "Host: $host\r\n";  
           $out .= 'Content-Length: '.strlen($post)."\r\n";  
           $out .= "Connection: Close\r\n";  
           $out .= "Cache-Control: no-cache\r\n";  
           $out .= "Cookie: $cookie\r\n\r\n";  
           $out .= $post;  
       } else {  
           $out = "GET $path HTTP/1.0\r\n";  
           $out .= "Accept: */*\r\n";  
           //$out .= "Referer: $boardurl\r\n";  
           $out .= "Accept-Language: zh-cn\r\n";  
           $out .= "User-Agent: $_SERVER[HTTP_USER_AGENT]\r\n";  
           $out .= "Host: $host\r\n";  
           $out .= "Connection: Close\r\n";  
           $out .= "Cookie: $cookie\r\n\r\n";  
       }  
       $fp = fsockopen(($ip ? $ip : $host), $port, $errno, $errstr, $timeout);  
       if(!$fp) return ''; else {  
           $header = $content = '';  
           stream_set_blocking($fp, $block);  
           stream_set_timeout($fp, $timeout);  
           fwrite($fp, $out);  
           $status = stream_get_meta_data($fp);  
           if(!$status['timed_out']) {//未超时  
               while (!feof($fp)) {  
                   $header .= $h = fgets($fp);  
                   if($h && ($h == "\r\n" ||  $h == "\n")) break;  
               }  
  
               $stop = false;  
               while(!feof($fp) && !$stop) {  
                   $data = fread($fp, ($limit == 0 || $limit > 8192 ? 8192 : $limit));  
                   $content .= $data;  
                   if($limit) {  
                       $limit -= strlen($data);  
                       $stop = $limit <= 0;  
                   }  
               }  
           }  
        fclose($fp);  
           return $returnHeader ? array($header,$content) : $content;  
       }  
    }  
	file_put_contents("tsxx_WxPay.txt", "\r\n--------------------------\r\n", FILE_APPEND);
	file_put_contents("tsxx_WxPay.txt", "\r\n收到微信回调充值通知:".date('Y-m-d H:i:s')."\r\n", FILE_APPEND);
	//$xml = $GLOBALS['HTTP_RAW_POST_DATA'];
	$msg = array();
	$postStr = file_get_contents('php://input');
	$msg = (array)simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
	file_put_contents("tsxx_WxPay.txt", "\r\n返回全部信息：".json_encode($msg)."\r\n", FILE_APPEND);
	file_put_contents("tsxx_WxPay.txt", "\r\n返回格式    ：".$msg."\r\n", FILE_APPEND);
	file_put_contents("tsxx_WxPay.txt", "\r\n返回数据条数：".count($msg)."\r\n", FILE_APPEND);
	file_put_contents("tsxx_WxPay.txt", "\r\nappid       ：".$msg['appid']."\r\n", FILE_APPEND);
	file_put_contents("tsxx_WxPay.txt", "\r\n支付结果    ：".$msg['result_code']."\r\n", FILE_APPEND);
	file_put_contents("tsxx_WxPay.txt", "\r\n商户号      ：".$msg['mch_id']."\r\n", FILE_APPEND);
	file_put_contents("tsxx_WxPay.txt", "\r\n订单信息    ：".$msg['attach']."\r\n", FILE_APPEND);
	file_put_contents("tsxx_WxPay.txt", "\r\n交易单号    ：".$msg['transaction_id']."\r\n", FILE_APPEND);
	// file_put_contents("tsxx_WxPay.txt", "\r\n".var_export($postObj,true)."\r\n", FILE_APPEND);
	file_put_contents("tsxx_WxPay.txt", "\r\n--------------------------\r\n", FILE_APPEND);
	if($msg['result_code']=='SUCCESS')
	{
        
        //收到支付成功信息
		$json=explode(',',$msg['attach']);//获取orderId列表

		$cart_list=$json;
		$user_id='0';
		$ip='';
		$time=time();
		$total_fee=$msg['total_fee']/100;
		$money=$total_fee;
		$trade_no=$msg['out_trade_no'];
		$dingdan=$trade_no;
		// if(isset($_REQUEST['ip'])) $ip=$_REQUEST['ip'];
		//验证是否重复下单
		$sql="select * from ".$oto."_money_record where orderNo LIKE '%$dingdan%'";
		$result=$db->query($sql);
		while($row=$result->fetch_assoc()){
			$isPay=$row;//将取得的所有数据赋值给person_info数组
		}
		if(isset($isPay))
		{
			die();
		}

		//转换获取的商品数据
		$goods_list=explode(',',$cart_list);
		for($i=0;$i<count($goods_list);$i++)
		{
			$lin=0;
			$lin=explode('_',$goods_list[$i]);
			if($i==0)
			{

				$user_id=$lin[0];
				$goodsId_list[$i]=$lin[1];
				$num_list[$i]=$lin[2];
			} 
			else
			{
				$goodsId_list[$i]=$lin[0];
				$num_list[$i]=$lin[1];
			}
			
		}
		//查询用户信息
		$sql="select * from `".$oto."_users` where userId='{$user_id}'";
		$result=$db->query($sql);
		while($row=$result->fetch_assoc()){
			$users=$row;//将取得的所有数据赋值给person_info数组
		}
		$sql="select * from `".$oto."_money_record` where orderNo LIKE '%$trade_no%'";
		$result=$db->query($sql);
		while($row=$result->fetch_assoc()){
			$money_record=$row;//将取得的所有数据赋值给person_info数组
		}
		if(isset($money_record))
		{
			echo "success";
			die();
		}
		$balance=$users['userMoney']+$money;
		//验证商品
		$pay_money=0;
		for($i=0;$i<count($goodsId_list);$i++)
		{
			$sql="select * from `".$oto."_shoplist` as s where id='".$goodsId_list[$i]."'";
			$result=$db->query($sql);
			while($row=$result->fetch_assoc()){
				$shoplist[$i]=$row;//将取得的所有数据赋值给person_info数组
			}
			if(isset($shoplist[$i]))
			{
				if($num_list[$i]<=0)
				{
					$data[0]['pan']="false";
					$data[0]['msg']="参数错误";
					$data[0]['orderId']="[]";

					//增加消费记录
					$sql="INSERT INTO ".$oto."_money_record (`type`,`money`,`time`,`ip`,`orderNo`,`IncDec`,`userid`,`balance`,`remark`,`payWay`) VALUES ('5','$money','$time','$ip','$dingdan','1','$user_id','$balance','订单退款','1')";
					$result=$db->query($sql);
					//修改用户余额以及积分
					$sql="update ".$oto."_users set userMoney='{$balance}' where userId='{$user_id}'";
					$result=$db->query($sql);
					echo "success";
					//echo json_encode($data);
					die();
				}
				if($shoplist[$i]['shenyurenshu']<$num_list[$i])
				{
					$data[0]['pan']="false";
					$data[0]['msg']=$shoplist[$i]['title']."剩余人次不足 可购买：".$shoplist[$i]['shenyurenshu']."次";
					$data[0]['orderId']="[]";

					//增加消费记录
					$sql="INSERT INTO ".$oto."_money_record (`type`,`money`,`time`,`ip`,`orderNo`,`IncDec`,`userid`,`balance`,`remark`,`payWay`) VALUES ('5','$money','$time','$ip','$dingdan','1','$user_id','$balance','订单退款','1')";
					$result=$db->query($sql);
					//修改用户余额以及积分
					$sql="update ".$oto."_users set userMoney='{$balance}' where userId='{$user_id}'";
					$result=$db->query($sql);
					echo "success";
					//echo json_encode($data);
					die();
				}
				$pay_money+=$num_list[$i]*$shoplist[$i]['yunjiage'];
			}
		}
		// if($users['userMoney']<$pay_money)
		// {
		// 	$data[0]['pan']="false";
		// 	$data[0]['msg']="用户余额不足";
		// 	$data[0]['orderId']="[]";
		// 	echo json_encode($data);
		// 	die();
		// }
		if($pay_money==0)
		{
			$data[0]['pan']="false";
			$data[0]['msg']="订单金额异常";
			$data[0]['orderId']="[]";

			//增加消费记录
			$sql="INSERT INTO ".$oto."_money_record (`type`,`money`,`time`,`ip`,`orderNo`,`IncDec`,`userid`,`balance`,`remark`,`payWay`) VALUES ('5','$money','$time','$ip','$dingdan','1','$user_id','$balance','订单退款','1')";
			$result=$db->query($sql);
			//修改用户余额以及积分
			$sql="update ".$oto."_users set userMoney='{$balance}' where userId='{$user_id}'";
			$result=$db->query($sql);
			echo "success";
			//echo json_encode($data);
			die();
		}
		$data[0]['pan']="true";
		$data[0]['msg']="下单成功";

		//验证通过，开始下单操作
		for($k=0;$k<count($goodsId_list);$k++)
		{
			//查询用户信息
			$sql="select * from `".$oto."_users` where userId='{$user_id}'";
			$result=$db->query($sql);
			while($row=$result->fetch_assoc()){
				$users=$row;//将取得的所有数据赋值给person_info数组
			}
			//生成订单号
			$t=sprintf("%.3f",microtime(true));
			$t2=$t*1000;
			$sj=rand(1,9999);
			$sj=str_pad($sj,4,"0",STR_PAD_LEFT);
			$dingdan='A'.$t2.$sj.':'.$trade_no;
			//获取商品id
			$goods_id=$shoplist[$k]['id'];
			//获取云购码
			$z_qishu2=$shoplist[$k]['qishu'];
			$z_sid=$shoplist[$k]['sid'];
			$z_id=$shoplist[$k]['id'];
			$sql="select * from `".$oto."_shopcodes_1` where `s_id`='{$z_id}'";
			$result=$db->query($sql);
			while($row=$result->fetch_assoc()){
				$a2[]=$row;//将取得的所有数据赋值给person_info数组
			}
			$b2=unserialize($a2[0]['s_codes']);
			for($i=1;$i<count($a2);$i++)
			{
				$b2=array_merge($b2,unserialize($a2[$i]['s_codes']));
			}
			//$b2=unserialize($a2[0]['s_codes']);
			$money=$num_list[$k];
			$i=$shoplist[$k]['canyurenshu'];
			$max=$money+$i;
			$goucode='';
			for($i;$i<$max;$i++)
			{
				if($i==$max-1)
				{
					$goucode.=$b2[$i];
				}
				else
				{
					$goucode.=$b2[$i].",";
				}
			}
			//echo $goucode;//拿到幸运码
			//增加订单
			$username=$users['userName'];
			$img=$users['userPhoto'];
			$title=$shoplist[$k]['title'];
			$qishu=$shoplist[$k]['qishu'];
			$storeid=$shoplist[$k]['shop_id'];
			$lin_money=$money*$shoplist[$k]['yunjiage'];
			$sql="INSERT INTO ".$oto."_member_go_record (`code`,`username`,`uphoto`,`uid`,`shopid`,`shopname`,`shopqishu`,`gonumber`,`goucode`,`moneycount`,`pay_type`,`ip`,`status`,`time`,`storeid`) VALUES ('{$dingdan}','{$username}','{$img}','{$user_id}','{$goods_id}','{$title}','{$qishu}','{$money}','{$goucode}','{$lin_money}','微信支付','{$ip}','已付款,未发货,未完成','{$t}','{$storeid}')";
			$result1=$db->query($sql);
			$balance=$users['userMoney']-$lin_money;
			$hscore=$users['userScore']+$lin_money;
			//增加消费记录
			$sql="INSERT INTO ".$oto."_money_record (`type`,`money`,`time`,`ip`,`orderNo`,`IncDec`,`userid`,`balance`,`remark`,`payWay`) VALUES ('1','$lin_money','$time','$ip','$dingdan','0','$user_id','$balance','一元购微信下单','2')";
			$result2=$db->query($sql);
			//增加积分记录
			$sql="INSERT INTO ".$oto."_score_record (`userid`,`orderNo`,`score`,`totalscore`,`time`,`ip`,`IncDec`,`type`) VALUES ('$user_id','$dingdan','$lin_money','$hscore','$time','$ip','1','1')";
			$result3=$db->query($sql);
			//修改商品参与人数与剩余人数
			$canyurenshu=$shoplist[$k]['canyurenshu']+$money;
			$shenyurenshu=$shoplist[$k]['shenyurenshu']-$money;
			$sql="update ".$oto."_shoplist set canyurenshu='{$canyurenshu}',shenyurenshu='{$shenyurenshu}' where id='{$goods_id}'";
			//file_put_contents("tsxx.txt", "\r\n用户:".$user_id."\r\n当前循环的goods_id：".$goods_id."\r\n购买前剩余:".$ci[$k]['shenyurenshu']."参与:".$ci[$k]['canyurenshu']."\r\n".$sql."\r\nselect * from `go_shoplist` where `id`='".$goods_id."' LIMIT 1\t\n", FILE_APPEND);
			$result4=$db->query($sql);
			//修改用户余额以及积分
			$sql="update ".$oto."_users set userScore='{$hscore}' where userId='{$user_id}'";
			$result5=$db->query($sql);

			//************开奖*************//
			
			
			if($result1 && $result2 && $result3 && $result4 && $result5)
			{
				$data[0]['orderId'][$k]=$dingdan.'';
				echo "success";
			}
			else
			{
				if($result1)
				{
					$sql="DELETE FROM `".$oto."_member_go_record` WHERE `code`='{$dingdan}'";
					$result1=$db->query($sql);
				}
				if($result2)
				{
					$sql="DELETE FROM `".$oto."_money_record` WHERE `orderNo`='{$dingdan}'";
					$result2=$db->query($sql);
				}
				if($result3)
				{
					$sql="DELETE FROM `".$oto."_score_record` WHERE `orderNo`='{$dingdan}'";
					$result3=$db->query($sql);
				}
				if($result4)
				{
					$sql="update ".$oto."_shoplist set canyurenshu='".$shoplist[$k]['canyurenshu']."',shenyurenshu='".$shoplist[$k]['shenyurenshu']."' where id='{$goods_id}'";
					$result4=$db->query($sql);
				}
				if($result5)
				{
					$sql="update ".$oto."_users set userScore='".$users['userScore']."' where userId='{$user_id}'";
					$result5=$db->query($sql);
				}
				$data[0]['pan']="false";
				$data[0]['msg']="操作异常";
				$balance=$users['userMoney']+$money;
				//增加消费记录
				$sql="INSERT INTO ".$oto."_money_record (`type`,`money`,`time`,`ip`,`orderNo`,`IncDec`,`userid`,`balance`,`remark`,`payWay`) VALUES ('5','$money','$time','$ip','$dingdan','1','$user_id','$balance','订单退款','1')";
				$result=$db->query($sql);
				//修改用户余额以及积分
				$sql="update ".$oto."_users set userMoney='{$balance}' where userId='{$user_id}'";
				$result=$db->query($sql);
				echo "success";
			}
			if($shenyurenshu==0)
			{
				$lin_pan=httpRequest($WEB_PATH.'/index.php?m=Go&c=Cart&a=zdsh');
				// pay_insert_shop($shoplist[$k],'add');
			}
		}
	}
?>